// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const _ = db.command
const $ = _.aggregate
// 云函数入口函数
exports.main = async (event, context) => {
  if (event.type == 'select') {
    return await db.collection('diary')
      .aggregate()
      .project({
        _id: 1,
        _openid: 1,
        createTime: 1,
        diary: 1,
        lover_openid: 1,
        time: 1,
        type: 1,
        urls: 1
      })
      .sort({
        createTime: -1
      })
      .lookup({
        from: 'users',
        localField: '_openid',
        foreignField: '_openid',
        as: 'diaryedBy',
      })
      .match(_.or([
        { _openid: event._openid },
        { lover_openid: event._openid }
      ]))
      .skip(event.skiplength)
      .limit(10)
      .end()
  } else if (event.type == 'update') {
    return await db.collection('diary').doc(event.diary._id)
      .update({
        data: {
          diary: event.diary.diary,
          type: event.diary.type,
          urls: event.diary.urls
        }
      })
  } else if (event.type == 'delete') {
    cloud.deleteFile({
      fileList: event.diary.urls,
      success: ()=>{},
      fail: ()=>{}
    })
    return await db.collection('diary').doc(event.diary._id).remove()
  }
}